<template>
  <div class="profile">
    <el-container>
      <el-header>
        <div class="header-content">
          <div class="header-left">
            <el-button type="primary" @click="router.push('/')">
              <el-icon><ArrowLeft /></el-icon>
              返回主页
            </el-button>
          </div>
          <div class="header-right">
            <h2>个人信息</h2>
          </div>
        </div>
      </el-header>
      <el-main>
        <el-card class="profile-card">
          <template #header>
            <div class="card-header">
              <span>基本信息</span>
            </div>
          </template>
          <div class="profile-content">
            <div class="avatar-section">
              <el-avatar 
                :size="100" 
                :src="userInfo.imageUrl" 
                @error="() => true"
              >
                <img src="https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png" />
              </el-avatar>
              <el-upload
                class="avatar-uploader"
                :show-file-list="false"
                :before-upload="beforeAvatarUpload"
                :http-request="handleAvatarUpload"
              >
                <el-button type="primary">更换头像</el-button>
              </el-upload>
            </div>

            <el-form :model="userInfo" label-width="120px">
              <el-form-item label="用户名">
                <el-input v-model="userInfo.userName" disabled />
              </el-form-item>
              <el-form-item label="昵称">
                <el-input v-model="userInfo.callName" />
              </el-form-item>
              <el-form-item label="手机号">
                <el-input v-model="userInfo.phoneNumber" disabled />
              </el-form-item>
              <el-form-item label="个人简介">
                <el-input type="textarea" v-model="userInfo.bio" :rows="3" />
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="handleSave">保存修改</el-button>
              </el-form-item>
            </el-form>
          </div>
        </el-card>
      </el-main>
    </el-container>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { ArrowLeft } from '@element-plus/icons-vue'
import { getUserProfile, updateUserProfile, uploadAvatar } from '@/api/user'
import { useRouter } from 'vue-router'

const router = useRouter()

const userInfo = ref({
  userId: null,
  userName: '',
  callName: '',
  phoneNumber: '',
  imageUrl: '',
  bio: ''
})

const loadUserProfile = async () => {
  try {
    console.log('开始加载用户信息')
    const res = await getUserProfile()
    console.log('获取到的用户信息原始数据:', res)
    
    // 检查响应是否为对象且包含必要字段
    if (res && typeof res === 'object') {
      // 如果响应直接包含用户信息字段
      if (res.userId) {
        console.log('直接获取到用户信息:', res)
        userInfo.value = res
        console.log('更新后的userInfo:', userInfo.value)
        return
      }
      
      // 如果响应包含 code 和 data
      if (res.code === 1 && res.data) {
        console.log('用户信息数据:', res.data)
        userInfo.value = res.data
        console.log('更新后的userInfo:', userInfo.value)
        return
      }
    }
    
    console.log('获取用户信息失败: 数据格式不正确')
    ElMessage.error('获取用户信息失败')
  } catch (error) {
    console.error('获取用户信息失败:', error)
    ElMessage.error('获取用户信息失败')
  }
}

const handleSave = async () => {
  try {
    // 发送所有需要更新的字段，包括头像URL
    const updateData = {
      userId: userInfo.value.userId,
      callName: userInfo.value.callName,
      bio: userInfo.value.bio,
      imageUrl: userInfo.value.imageUrl  // 添加头像URL
    }
    console.log('准备保存的数据:', updateData)
    await updateUserProfile(updateData)  // 不需要保存响应
    console.log('保存成功')
    
    ElMessage.success('保存成功')
    // 重新加载用户信息以确保显示最新数据
    await loadUserProfile()
  } catch (error) {
    console.error('保存失败:', error)
    ElMessage.error('保存失败')
  }
}

const handleAvatarUpload = async (options) => {
  try {
    console.log('开始上传头像，文件信息:', options.file)
    const res = await uploadAvatar(options.file)
    console.log('上传响应:', res)
    
    // 检查响应是否为字符串（直接返回的URL）
    if (typeof res === 'string') {
      console.log('上传成功，返回的URL:', res)
      userInfo.value.imageUrl = res
      console.log('更新后的userInfo:', userInfo.value)
      ElMessage.success('头像上传成功')
      return
    }

    // 处理对象格式的响应
    if (res.code === 1) {
      console.log('上传成功，返回的URL:', res.data)
      userInfo.value.imageUrl = res.data
      console.log('更新后的userInfo:', userInfo.value)
      ElMessage.success('头像上传成功')
    } else {
      console.log('上传失败:', res.message)
      ElMessage.error(res.message || '头像上传失败')
    }
  } catch (error) {
    console.error('头像上传出错:', error)
    ElMessage.error('头像上传失败')
  }
}

const beforeAvatarUpload = (file) => {
  const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isJPG) {
    ElMessage.error('上传头像图片只能是 JPG/PNG 格式!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('上传头像图片大小不能超过 2MB!')
    return false
  }
  return true
}

onMounted(() => {
  loadUserProfile()
})
</script>

<style scoped>
.profile {
  min-height: 100vh;
  background-color: #f5f7fa;
}

.el-header {
  padding: 0;
  background-color: #fff;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 1000;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 100%;
  padding: 0 20px;
}

.header-left {
  display: flex;
  align-items: center;
}

.header-right {
  display: flex;
  align-items: center;
}

.header-right h2 {
  margin: 0;
  color: #333;
}

.el-main {
  padding: 20px;
  max-width: 1400px;
  margin: 80px auto 0;
}

.profile-card {
  margin-bottom: 20px;
  min-width: 50vw;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
}

.card-header span {
  font-size: 18px;
  font-weight: bold;
}

.profile-content {
  padding: 20px 60px;
}

.avatar-section {
  text-align: center;
  margin-bottom: 40px;
}

.avatar-section .el-avatar {
  width: 120px;
  height: 120px;
}

.avatar-uploader {
  margin-top: 15px;
}

.el-form {
  max-width: 100%;
  margin: 0 auto;
}

.el-form-item {
  margin-bottom: 25px;
}

.el-input, .el-input__wrapper {
  width: 100%;
  font-size: 16px;
}

.el-input__inner {
  height: 45px;
}

.el-textarea__inner {
  min-height: 120px !important;
}

.el-form-item__label {
  font-size: 16px;
  padding-right: 30px;
}
</style> 